import React, { PureComponent } from 'react';
import { connect } from 'umi';
import { history } from 'umi';

import { Card, Input, Button, Form, message, Popover, Icon, Avatar } from 'antd';
import { formatMessage } from 'umi';
import { FormattedMessage } from 'umi';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { withRoutePage } from '@/utils/enhanceUtils';
import { clearLoginStates } from '@/utils/utils';
import pageTabUtil from '@/utils/pageTabUtil';

// 组件
import styles from './PasswordSettings.less';

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 3 }
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 8 }
    }
};
@withRoutePage
@connect(({ loading, personalCenter, user }) => ({
    personalCenter,
    loading: loading.models.personalCenter,
    user
}))
@Form.create({
    onFieldsChange(props, changedFields) {
        if (changedFields.newPassword && changedFields.newPassword.value) {
            props.form.validateFields(['confirmNewPassword'], { force: true });
        }
    }
})
class passwordSettings extends PureComponent {
    state = {
        isVisible: false
        // isConfirmVisible: false
    };

    componentDidMount() {
        // this.getUserData();
    }

    getPasswordStatus = () => {
        const { form } = this.props;
        const value = form.getFieldValue('newPassword');
        const checked = [];
        if (!value) return '';

        if (value.length >= 8 && value.length <= 20) {
            checked.push('step1');
        }
        if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
            checked.push('step2');
        }

        return checked.map(item => styles[item]).join(' ');
    };

    changeVisible = t => {
        const { isVisible } = this.state;
        const checked = [];
        const { value } = t.target;
        if (!value) return '';
        if (value.length >= 8 && value.length <= 20) {
            checked.push('step1');
        }
        if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*$/.test(value)) {
            checked.push('step2');
        }
        if (checked.length >= 2) {
            if (isVisible !== false) {
                this.setState({
                    isVisible: false
                });
            }
        } else if (isVisible !== true) {
            this.setState({
                isVisible: true
            });
        }
        // form.validateFields(['confirmNewPassword'], { force: true });
        return '';
    };

    getConfirmPasswordStatus = () => {
        const { form } = this.props;
        const newPassword = form.getFieldValue('newPassword');
        const confirmNewPassword = form.getFieldValue('confirmNewPassword');
        const checked = [];
        if (!confirmNewPassword) return '';

        if (newPassword !== confirmNewPassword) {
            checked.push('step1');
        }
        return checked.map(item => styles[item]).join(' ');
    };

    // changeConfirmVisible = t => {
    //     const { form } = this.props;
    //     const { isConfirmVisible } = this.state;
    //     const checked = [];
    //     const { value } = t.target;
    //     const newPassword = form.getFieldValue('newPassword');

    //     if (!value) return '';
    //     if (value !== newPassword) {
    //         checked.push('step1');
    //     }
    //     if (checked.length === 0) {
    //         this.setState({
    //             isConfirmVisible: false
    //         });
    //     } else {
    //         this.setState({
    //             isConfirmVisible: true
    //         });
    //     }
    //     return '';
    // };

    getUserData = () => {
        const { dispatch } = this.props;
        dispatch({
            type: 'personalCenter/getUser'
        });
    };

    checkConfirm = (rule, value, callback) => {
        const { form } = this.props;
        if (!value) {
            callback(formatMessage({ id: 'form.confirmPassword.placeholder' }));
        } else if (value !== form.getFieldValue('newPassword')) {
            callback(formatMessage({ id: 'validation.password.twice' }));
        } else {
            callback();
        }
    };

    handleSave = () => {
        const { form, dispatch } = this.props;
        form.validateFields(['password', 'newPassword', 'confirmNewPassword'], { force: true }, (err, values) => {
            if (!err) {
                // console.log('Received values of form: ', values);
                dispatch({
                    type: 'personalCenter/editPassword',
                    payload: {
                        values
                    },
                    callback: data => {
                        if (data.code === 10000) {
                            form.resetFields();
                            message.success('修改成功', 3, () => {
                                clearLoginStates();
                                history.push('/user/login');
                            });
                        } else if (data.code === 20011) {
                            message.error('不能频繁重置密码');
                        } else if (data.code === 20012) {
                            message.error('旧密码不正确');
                        } else if (data.code === 10201) {
                            message.error('密码需包含大小写字母、数字，长度在8-20位');
                        }
                    }
                });
            }
        });
    };

    handleCancel = () => {
        pageTabUtil.closeTab();
    };

    render() {
        const { isVisible } = this.state;
        const {
            user,
            form: { getFieldDecorator }
        } = this.props;
        // const user = JSON.parse(localStorage.getItem('user'));
        const userInfo = user.currentUser;
        const { avatarFile } = user?.avatarFile;
        return (
            <PageHeaderWrapper>
                <Card bordered={false} style={{ marginBottom: 12 }}>
                    <div className={styles.userInfo}>
                        <Avatar
                            style={{ flex: '0 0 72px' }}
                            icon="user"
                            src={avatarFile && avatarFile.length > 0 ? avatarFile[0].url : ''}
                            size={72}
                        />
                        <div className={styles.fontbox}>
                            <div className={styles.name}>{userInfo.employeeName}</div>
                            <ul>
                                <li>用户名：{userInfo.userName}</li>
                                <li>工号：{userInfo.userNo}</li>
                                <li>邮箱：{userInfo.email}</li>
                            </ul>
                        </div>
                    </div>
                </Card>
                <Card
                    title={formatMessage({
                        id: 'form.passowrdSetting'
                    })}
                    bordered={false}
                >
                    <Form layout="horizontal" {...formItemLayout}>
                        <Form.Item
                            label={formatMessage({
                                id: 'form.oldPassword.label'
                            })}
                        >
                            {getFieldDecorator('password', {
                                rules: [
                                    {
                                        required: true,
                                        message: formatMessage({
                                            id: 'form.oldPassword.placeholder'
                                        })
                                    }
                                ]
                            })(
                                <Input.Password
                                    placeholder={formatMessage({
                                        id: 'form.oldPassword.placeholder'
                                    })}
                                />
                            )}
                        </Form.Item>
                        <Form.Item
                            label={formatMessage({
                                id: 'form.newPassword.label'
                            })}
                        >
                            <Popover
                                getPopupContainer={node => {
                                    if (node && node.parentNode) {
                                        return node.parentNode;
                                    }
                                    return node;
                                }}
                                content={
                                    <div
                                        style={{ padding: 0 }}
                                        className={`${styles.validatePassword} ${this.getPasswordStatus()}`}
                                    >
                                        <div>
                                            <Icon type="check-circle" theme="filled" />
                                            <FormattedMessage id="form.passwordRuleStep1.validate" />
                                        </div>
                                        <div>
                                            <Icon type="check-circle" theme="filled" />
                                            <FormattedMessage id="form.passwordRuleStep2.validate" />
                                        </div>
                                    </div>
                                }
                                placement="right"
                                visible={isVisible}
                            >
                                {getFieldDecorator('newPassword', {
                                    rules: [
                                        {
                                            required: true,
                                            message: formatMessage({
                                                id: 'form.newPassword.placeholder'
                                            })
                                        }
                                    ]
                                })(
                                    <Input.Password
                                        placeholder={formatMessage({
                                            id: 'form.newPassword.placeholder'
                                        })}
                                        onChange={e => this.changeVisible(e)}
                                    />
                                )}
                            </Popover>
                        </Form.Item>
                        <Form.Item
                            label={formatMessage({
                                id: 'form.confirmPassword.label'
                            })}
                        >
                            {getFieldDecorator('confirmNewPassword', {
                                rules: [
                                    {
                                        required: true,
                                        validator: this.checkConfirm
                                    }
                                ]
                            })(
                                <Input.Password
                                    placeholder={formatMessage({
                                        id: 'form.newPassword.placeholder'
                                    })}
                                />
                            )}
                        </Form.Item>
                        <Form.Item
                            wrapperCol={{
                                xs: { span: 24, offset: 0 },
                                sm: { span: 8, offset: 3 }
                            }}
                        >
                            <Button type="primary" onClick={this.handleSave}>
                                {formatMessage({
                                    id: 'btn.orgEdit.save'
                                })}
                            </Button>
                            <Button style={{ marginLeft: '20px' }} onClick={this.handleCancel}>
                                {formatMessage({
                                    id: 'btn.orgEdit.cancel'
                                })}
                            </Button>
                        </Form.Item>
                    </Form>
                </Card>
            </PageHeaderWrapper>
        );
    }
}

export default passwordSettings;
